<template>

  <template v-if="loading"><van-skeleton title :row="3" /></template>

  <template v-else>
    <DefaultCardHead :headinfo="headinfo"></DefaultCardHead>
    <van-cell-group inset class="L-margin-top-20">
      <div class="L-detail-title-row">
        <span class="L-text L-primary-text-color">
          <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
          {{currentActionName}}
        </span>
        <div>
          <span class="L-schedule-btn" @click="getCurrentActionData('new')" v-if="isCanAdd">添加一条</span>
          <span class="L-schedule-btn" @click="handleSkip" v-if="currentAction?.canskip" style="margin-left:5px">跳过</span>
        </div>
      </div>
      <div v-for="(item,index) in actionArr" :key="index" style="border-bottom:10px solid #F0F2F5;">
        <div v-for="(hitem,hindex) in item?.head" :key="hindex">
          <FormInput scene="action" v-for="(fitem,findex) in hitem.groupvalue" :key="findex" :formItem="fitem" @handleChange="handleChange"></FormInput>
        </div>
      </div>
    </van-cell-group>

    <div class="roundCir" v-if="currentAction.actionType==='签到'" @click="handleSubmit">签到</div>
    <div class="roundCir" v-else-if="currentAction.actionType==='签退'">签退</div>
    <template v-else>
      <div class="L-bottom-space"></div>
      <div class="L-bottom-row">
        <van-button type="primary" block style="width: 90%;" @click="handleSubmit">提交</van-button>
      </div>
    </template>
  </template>

</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

import { apiConfigurable } from "@/request/api/api";
import DefaultCardHead from "@/components/base/Card/DefaultCardHead.vue";
import FormInput from "@/components/base/Form/FormInput.vue";
import { closeToast, showLoadingToast } from "vant";

onMounted(() => {
  getData();
});

const loading = ref(false);
const headinfo = ref({});
const currentActionId = ref(route.query.actionid || "");
const currentActionStates = ref("");
const currentActionName = ref("");
import type {actionVO} from "@/interface/interface"
const currentAction = ref<actionVO>({});
const currentActionIndex = ref(0);
const scenarioArr = ref([]);
const scenarioId = ref("");

function getData() {
  const { idobject, itemid } = route.query;
  const url = idobject + ".check.do";
  const data = {
    [idobject + "_id"]: itemid,
  };
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  loading.value = true;

  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      const { jsondata } = res.data;
      headinfo.value = jsondata.headinfo;
      scenarioArr.value = jsondata.scenario.scenarioInfo;
      scenarioId.value = jsondata.scenario.scenarioId;
      
      currentAction.value = jsondata.scenario.scenarioInfo.find((item, index) =>
        getCurrentAction(item, index)
      );
      closeToast();
      let operate = currentAction.value.toPage || 'new';
      
      getCurrentActionData(operate);

     
    }
  });
}

function getCurrentAction(item, index) {
  if (currentActionId.value) {
    if (item.actionId === currentActionId.value) {
      currentActionIndex.value = index;
      currentActionStates.value = item.states;
      currentActionName.value = item.actionName;
    }
    return item.actionId === currentActionId.value;
  } else {
    if (item.ended === false) {
      currentActionIndex.value = index;
      currentActionStates.value = item.states;
      currentActionName.value = item.actionName;
    }
    return item.ended === false;
  }
}

// 字段值发生变化
function handleChange(item, value, valuehidden = "") {
  item.value = value;
  if (valuehidden) {
    item.valuehidden = valuehidden;
  }
}

const actionArr = ref([]);
const isCanAdd = ref(false);

let actionItem = {};

function getCurrentActionData(operate: string) {
  const { idobject, itemid } = route.query;
  const url = "scenario.getaction.do";
  const { toBo: sobject, fields, toId, zdys } = currentAction.value;
  



  if (operate === "edit") {
    const toIdArr = JSON.parse(toId);
    const promiseArr = [];
    for (let i = 0; i < toIdArr.length; i++) {
      const data = {
        sobject,
        [sobject + "_id"]: toIdArr[i],
        fields: JSON.stringify(fields),
        headid: itemid,
        headobject: idobject,
        zdys: JSON.stringify(zdys),
      };
      promiseArr.push(apiConfigurable(url, data));
    }

    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
      duration: 0,
    });
    Promise.all(promiseArr)
      .then((res) => {
        if (res.every((item) => item.code === 0)) {
          res.forEach((item) => {
            item.data.jsondata["operate"] = operate;
            actionArr.value.push(item.data.jsondata);
          });
          isCanAdd.value = res[0].data.jsondata.newline;

          closeToast();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (operate === "new") {
    const data = {
      sobject,
      fields: JSON.stringify(fields),
      headid: itemid,
      headobject: idobject,
      zdys: JSON.stringify(zdys) ,
    };
    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
      duration: 0,
    });
    apiConfigurable(url, data)
      .then((res) => {
        if (res.code === 0) {
          res.data.jsondata["operate"] = operate;
          actionArr.value.push(res.data.jsondata);
          isCanAdd.value = res.data.jsondata.newline;
          closeToast();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
}

interface submitParams {
  [key: string]: any;
}
//提交
function handleSubmit() {
  const url = "scenario.getaction.do";
  const { toBo: idobject } = currentAction.value;
  const submitData = actionArr.value;
  const promiseArr = [];

  for (let i = 0; i < submitData.length; i++) {
    const data: submitParams = {};
    data[idobject + "_id"] = submitData[i][idobject + "_id"];
    for (let groupindex in submitData[i].head) {
      let itemgroup = submitData[i].head[groupindex].groupvalue;
      for (let itemindex in itemgroup) {
        let itemdata = itemgroup[itemindex];
        if (itemdata.sUIType === "ref") {
          data[itemdata.idObject + "_" + itemdata.sField] =
            itemdata.valuehidden;
          data[itemdata.idObject + "_" + itemdata.sField + "_ref"] =
            itemdata.value;
        } else if (itemdata.sUIType === "enum") {
          data[itemdata.idObject + "_" + itemdata.sField] =
            itemdata.valuehidden;
          data[itemdata.idObject + "_" + itemdata.sField + "_enum"] =
            itemdata.value;
        } else if (
          itemdata.sUIType === "file" ||
          itemdata.sUIType === "picture"
        ) {
          data[itemdata.idObject + "_" + itemdata.sField] =
            itemdata.valuehidden;
          data[itemdata.idObject + "_" + itemdata.sField + "_title"] =
            itemdata.value;
        } else {
          data[itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
        }
      }
    }

    const url = `${idobject}.${submitData[i].operate}save.do`;

    promiseArr.push(apiConfigurable(url, data));
  }

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  Promise.all(promiseArr).then((res) => {
    if (res.every((item) => item.code === 0)) {
      handleSave("end");
      closeToast();
    }
  });
}

//跳过
function handleSkip() {
  handleSave("skip");
}

async function handleSave(states = "end") {
  const { idobject, itemid } = route.query;
  const { actionId: idaction, toBo } = currentAction.value;
  const toiddata = actionArr.value.map((item) => {
    return item[`${toBo}_id`];
  });

  let data = {
    idscenario: scenarioId.value, //场景ID
    idaction, //动作ID
    toobject: toBo, //动作对象
    toiddata: JSON.stringify(toiddata), //动作对象id数组
    sobject: idobject,
    iddata: itemid,
    states: states,
    ended: false,
  };
  const saveLogRes = await savelog(data);
  if (saveLogRes.code === 0) {
    if (scenarioArr.value.length > currentActionIndex.value + 1) {
      data["ended"] = false;
    } else {
      data["ended"] = true;
    }
    scenarioEnd(data);
  }
}

function savelog(data) {
  const url = "scenario.savelog.do";
  return apiConfigurable(url, data);
}

function scenarioEnd(data) {
  const url = "scenario.end.do";
  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      // 路由当中有actionId代表编辑已经操作过的步骤,操作结束后要返回上一页
      if (currentActionId.value) {
        router.go(-1);
        return;
      }

      //data.ended代表当前场景是否完成,true代表已完成(返回上一页),false代表未完成(进入下一个动作)
      if (!data.ended) {
        const { idobject, itemid, stitle } = route.query;
        const query = {
          idobject,
          itemid,
          stitle,
        };
        actionArr.value = [];
        getData();
      } else {
        router.go(-1);
      }
    }
  });
}
</script>

<style scoped>
.roundCir {
  width: 134px;
  height: 134px;
  background: linear-gradient(180deg, #fdc75b 0%, #ff9d02 100%);
  filter: drop-shadow(0 0 9px #ffc523cc);
  border-radius: 50%;
  border: none;
  color: #fff;
  margin: 30px auto;
  font-size: 20px;

  display: flex;
  justify-content: center;
  align-items: center;
}
</style>